//
//  ZQPictureCollectionController.swift
//  ZQWeibo
//
//  Created by summer的Dad on 16/11/22.
//  Copyright © 2016年 summer的Dad. All rights reserved.
//

import UIKit

let colCont : CGFloat = 3

let  PicMargin : CGFloat = 4

let itmeWith : CGFloat = (ScreenWidth - (colCont + 1 ) * PicMargin) / colCont
//最大张数
private let maxCount = 3

private let reuseIdentifier = "Cell"

class ZQPictureCollectionController: UICollectionViewController {

    lazy var contentImageArr : [UIImage]  = [UIImage]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
     
        self.collectionView!.register(picturCollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        self.collectionView?.backgroundColor = UIColor.white
        
 
    }
  
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        let count  = self.contentImageArr.count == maxCount ? 0 : 1
        
        return count + self.contentImageArr.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! picturCollectionCell
        
        cell.delegate = self
        
        
        //fuzhi
        if indexPath.item == self.contentImageArr.count {
            
            cell.image = nil
        }else{
            
            cell.image = self.contentImageArr[indexPath.item]
            
        }
    
        
    
        return cell
      }
   

    
}

        //遵守协议
    extension ZQPictureCollectionController : ZQPictureCollectionControllerDelegate{
        
        //添加按钮
        func addpicture(cell: picturCollectionCell?) {
            //拿到控制器
            let pickerController = UIImagePickerController()
            //设置代理必须练导航一起设置
            pickerController.delegate = self
            //调用代理方法
            self.present(pickerController, animated: true, completion: nil)
        }
        
        
        //删除按钮
        func removepicture(cell: picturCollectionCell) {
           
            guard let clickImage = collectionView?.indexPath(for: cell)else{
                
                return
            }
            
            self.contentImageArr.remove(at: clickImage.item)
            

            //刷新
            self.collectionView?.reloadData()
            
       
            // 没有图片隐藏
            self.view.isHidden = self.contentImageArr.count == 0
     
        }
      
        
     }

       //图片选择器的代理

        extension ZQPictureCollectionController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{
            
            func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
                
                //拿到图片
                let  image = info[UIImagePickerControllerOriginalImage] as! UIImage
                
                self.contentImageArr.append(image.scaleImage(widgth: ScreenWidth))
                
                dismiss(animated:true , completion:{
                    
                })
                //在外面刷新
                self.collectionView?.reloadData()
                
            }
            
          
        }



        //定义代理传递事件
        @objc protocol ZQPictureCollectionControllerDelegate : NSObjectProtocol{
            
            @objc optional func  addpicture(cell : picturCollectionCell?)
            
            
            @objc optional func  removepicture(cell : picturCollectionCell)
            
            
        }


    class picturCollectionCell : UICollectionViewCell {
        
    weak var delegate : ZQPictureCollectionControllerDelegate?
        
        
        var image : UIImage?{
            
            didSet{
                 addBten.setImage(image, for: .normal)
                
                
                removeBtn.isHidden = image == nil
            
            }
        }
        
        
        
        //按钮点击事件
        @objc private  func addimageBrn(){
            
            //避免重复添加
            if image != nil{

                return
            }
            
            
            delegate?.addpicture?(cell: self)
            
        }
        @objc private  func removeImageBtn(){
            
            delegate?.removepicture?(cell: self)
            
        }
        
        
        //init
        override init(frame: CGRect) {

          super.init(frame: frame)
          setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        

        
        
        
       //进入UI
        func setupUI(){
        
            self.contentView.addSubview(addBten)
            
            self.contentView.addSubview(removeBtn)
            
            
            //约束
            
            addBten.snp.makeConstraints { (make) in
                
                make.edges.equalTo(self.contentView)
            }
            removeBtn.snp.makeConstraints { (make) in
                make.trailing.top.equalTo(addBten)
            }
            contentView.backgroundColor = randomColor()
            
            //监听事件
            addBten.addTarget(self, action: #selector(addimageBrn), for: .touchUpInside)
            removeBtn.addTarget(self, action: #selector(removeImageBtn), for: .touchUpInside)
            
        }
        
        

        //加载控件
        lazy var addBten : UIButton = {
            let btn = UIButton()
            
            btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
            btn.contentMode = .scaleAspectFill
            
            
            return btn
            
        }()
        lazy var removeBtn : UIButton = {
            
            let btn = UIButton()
            
            btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
            return btn
        }()
        
        
        
        
        
       }
  



